package service

import (
	"sdc/repository/db/model"

	"gorm.io/gorm"
)

type ProjectAuditService struct {
	db *gorm.DB
}

func NewProjectAuditService(db *gorm.DB) *ProjectAuditService {
	return &ProjectAuditService{db: db}
}

// AuditProject 审核项目
func (s *ProjectAuditService) AuditProject(projectID uint64, status int8, remark string) error {
	return s.db.Transaction(func(tx *gorm.DB) error {
		// 检查项目是否存在且状态为待审核
		var project model.Project
		if err := tx.First(&project, projectID).Error; err != nil {
			if err == gorm.ErrRecordNotFound {
				return ErrProjectNotFound
			}
			return err
		}

		if project.Status != 0 { // 0表示待审核状态
			return ErrProjectStatusInvalid
		}

		// 更新项目状态
		if err := tx.Model(&project).Updates(map[string]interface{}{
			"status": status,
			"remark": remark,
		}).Error; err != nil {
			return err
		}

		// 记录审核日志
		auditLog := &model.ProjectAuditLog{
			ProjectID: projectID,
			Status:    status,
			Remark:    remark,
		}
		if err := tx.Create(auditLog).Error; err != nil {
			return err
		}

		// 如果审核通过，创建项目时间线
		if status == 1 { // 1表示审核通过
			timeline := &model.ProjectTimeline{
				ProjectID: projectID,
				Type:      1, // 1表示项目开始
				Content:   "项目审核通过，开始筹款",
			}
			if err := tx.Create(timeline).Error; err != nil {
				return err
			}
		}

		return nil
	})
}
